package com.wf.classRoomTest.customer;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class BoundedBufferTest {

    private BoundedBuffer buffer;

  /*  @Before
    public void setUp() {
        buffer = new BoundedBuffer(3);
    }*/

    @Test
    public void testPutAndTake() throws InterruptedException {
        // Test putting and taking values from the buffer
        buffer.put(1);
        buffer.put(2);
        buffer.put(3);
        assertEquals(1, buffer.take());
        assertEquals(2, buffer.take());
        assertEquals(3, buffer.take());
    }

    @Test
    public void testBufferFull() throws InterruptedException {
        // Test what happens when the buffer is full
        buffer.put(1);
        buffer.put(2);
        buffer.put(3);
        try {
            buffer.put(4);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // restore interrupted status
        }
        assertEquals(1, buffer.take());
        buffer.put(4); // Should not throw InterruptedException
    }

    @Test
    public void testBufferEmpty() throws InterruptedException {
        // Test what happens when the buffer is empty
        try {
            buffer.take();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // restore interrupted status
        }
        buffer.put(1);
        assertEquals(1, buffer.take());
    }

    @Test
    public void testMultipleProducersAndConsumers() {

                final BoundedBuffer buffer = new BoundedBuffer(5); // 设置缓冲区容量为5

                // 创建生产者线程
                Thread producerThread = new Thread(() -> {
                    try {
                        for (int i = 0; i < 10; i++) {
                            buffer.put(i); // 生产者不断地向缓冲区放入元素
                            Thread.sleep(1000); // 模拟生产过程
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });

                // 创建消费者线程
                Thread consumerThread = new Thread(() -> {
                    try {
                        for (int i = 0; i < 10; i++) {
                            buffer.take(); // 消费者不断地从缓冲区取出元素
                            Thread.sleep(1500); // 模拟消费过程
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });

                // 启动生产者和消费者线程
                producerThread.start();
                consumerThread.start();
            }
        }



